---
category: Level 2 — Intermediate
created: '2020-03-17'
keywords:
title: Export a table to csv
updated: '2021-05-07'
---

Assume that we have a `table` element and a `button` for exporting the table cells to CSV as following:

```html
<table id="exportMe" class="table">
    ...
</table>

<button id="export">Export</button>
```

## Export the table cells to CSV

The function below exports all the cells of `table` to CSV format. First, we [select](https://phuoc.ng/collection/html-dom/select-an-element-or-list-of-elements/) all the rows, [loop](https://phuoc.ng/collection/html-dom/loop-over-a-nodelist/) over them and export each row to CSV.

In each row, we go through all cells, and retrive their [text content](https://phuoc.ng/collection/html-dom/get-the-text-content-of-an-element/).

```js
const toCsv = function (table) {
    // Query all rows
    const rows = table.querySelectorAll('tr');

    return [].slice
        .call(rows)
        .map(function (row) {
            // Query all cells
            const cells = row.querySelectorAll('th,td');
            return [].slice
                .call(cells)
                .map(function (cell) {
                    return cell.textContent;
                })
                .join(',');
        })
        .join('\n');
};
```

## Download the CSV

The function below creates a fake `a` element whose content is `text` and triggers the `click` event.
For more information, you can visit the [Download a file](https://phuoc.ng/collection/html-dom/download-a-file/) post.

```js
const download = function (text, fileName) {
    const link = document.createElement('a');
    link.setAttribute('href', `data:text/csv;charset=utf-8,${encodeURIComponent(text)}`);
    link.setAttribute('download', fileName);

    link.style.display = 'none';
    document.body.appendChild(link);

    link.click();

    document.body.removeChild(link);
};
```

The last thing is to connect all pieces together. We just need to [handle](https://phuoc.ng/collection/html-dom/attach-or-detach-an-event-handler/) the `click` event of the _Export_ button:

```js
const table = document.getElementById('exportMe');
const exportBtn = document.getElementById('export');

exportBtn.addEventListener('click', function () {
    // Export to csv
    const csv = toCsv(table);

    // Download it
    download(csv, 'download.csv');
});
```

## Demo

<Playground>
```html
<div style="padding: 1rem">
    <table id="exportMe" class="table">
        <thead>
            <tr>
                <th data-type="number">No.</th>
                <th>First name</th>
                <th>Last name</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>1</td>
                <td>Andrea</td>
                <td>Ross</td>
            </tr>
            <tr>
                <td>2</td>
                <td>Penelope</td>
                <td>Mills</td>
            </tr>
            <tr>
                <td>3</td>
                <td>Sarah</td>
                <td>Grant</td>
            </tr>
            <tr>
                <td>4</td>
                <td>Vanessa</td>
                <td>Roberts</td>
            </tr>
            <tr>
                <td>5</td>
                <td>Oliver</td>
                <td>Alsop</td>
            </tr>
            <tr>
                <td>6</td>
                <td>Jennifer</td>
                <td>Forsyth</td>
            </tr>
            <tr>
                <td>7</td>
                <td>Michelle</td>
                <td>King</td>
            </tr>
            <tr>
                <td>8</td>
                <td>Steven</td>
                <td>Kelly</td>
            </tr>
            <tr>
                <td>9</td>
                <td>Julian</td>
                <td>Ferguson</td>
            </tr>
            <tr>
                <td>10</td>
                <td>Chloe</td>
                <td>Ince</td>
            </tr>
        </tbody>
    </table>

    <button class="button" id="export">Export</button>
</div>
```

```css
.table {
    border-collapse: collapse;
}
.table,
.table th,
.table td {
    border: 1px solid #ccc;
}
.table th,
.table td {
    padding: 0.5rem;
}
.button {
    background-color: #63b3ed;
    border: none;
    color: #fff;
    cursor: pointer;
    margin-top: 1rem;
    padding: 0.5rem 0.75rem;
}
```

```js
document.addEventListener('DOMContentLoaded', function () {
    const table = document.getElementById('exportMe');
    const exportBtn = document.getElementById('export');

    const toCsv = function (table) {
        // Query all rows
        const rows = table.querySelectorAll('tr');

        return [].slice
            .call(rows)
            .map(function (row) {
                // Query all cells
                const cells = row.querySelectorAll('th,td');
                return [].slice
                    .call(cells)
                    .map(function (cell) {
                        return cell.textContent;
                    })
                    .join(',');
            })
            .join('\n');
    };

    const download = function (text, fileName) {
        const link = document.createElement('a');
        link.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(text));
        link.setAttribute('download', fileName);

        link.style.display = 'none';
        document.body.appendChild(link);

        link.click();

        document.body.removeChild(link);
    };

    exportBtn.addEventListener('click', function () {
        // Export to csv
        const csv = toCsv(table);

        // Download it
        download(csv, 'download.csv');
    });
});
```
</Playground>

## See also

-   [Attach or detach an event handler](https://phuoc.ng/collection/html-dom/attach-or-detach-an-event-handler/)
-   [Download a file](https://phuoc.ng/collection/html-dom/download-a-file/)
-   [Get the text content of an element](https://phuoc.ng/collection/html-dom/get-the-text-content-of-an-element/)
-   [Loop over a nodelist](https://phuoc.ng/collection/html-dom/loop-over-a-nodelist/)
-   [Select an element or list of elements](https://phuoc.ng/collection/html-dom/select-an-element-or-list-of-elements/)
